package com.yunbao.ioc.tx;

import com.yunbao.ioc.annotation.Transactional;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by louisyuu on 2020/3/4 下午3:19
 */
public class TransactionalAdviceInfo {
    private final static Map<Class<?>, Set<Method>> adviceMethods = new HashMap<>();


    public static Set<Method> getAdviceMethods(Class<?> clazz) {
        return adviceMethods.get(clazz);
    }


    public static Set<Method> add(Class<?> clazz, Method advice) {
        Set<Method> methods = adviceMethods.get(clazz);
        if (methods == null) {
            methods = new HashSet<>();
        }
        methods.add(advice);
        return adviceMethods.put(clazz, methods);
    }


    public static void add(Collection<Class<?>> classes) {
        classes.forEach(cls -> {
            Transactional tx = cls.getDeclaredAnnotation(Transactional.class);
            Set<Method> methods = Stream.of(cls.getDeclaredMethods()).collect(Collectors.toSet());
            if (tx != null) {
                adviceMethods.put(cls, methods);
            } else {
                methods.forEach(method -> {
                    Transactional mTx = method.getDeclaredAnnotation(Transactional.class);
                    if (mTx != null) {
                        add(cls, method);
                    }

                });
            }
        });

    }

}
